package com.ruoyi.contract.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.contract.domain.*;
import com.ruoyi.contract.domain.companyVo.CompanyName;
import com.ruoyi.contract.domain.invoiceVo.InvoiceExport;
import com.ruoyi.contract.domain.invoiceVo.InvoiceInfoVo;
import com.ruoyi.contract.domain.invoiceVo.SelectInvoiceVo;
import com.ruoyi.contract.mapper.*;
import com.ruoyi.contract.tools.InvoiceCode;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.contract.service.IInvoiceService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 发票Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-10-18
 */
@Service
public class InvoiceServiceImpl implements IInvoiceService 
{
    @Autowired
    private InvoiceMapper invoiceMapper;
    @Autowired
    private BelongingCompanyMapper belongingCompanyMinvoiceInformationMapper;
    @Autowired
    private InvoiceInformationMapper invoiceInformationMapper;
    @Autowired
    private InvoiceAttachmentMapper invoiceAttachmentMapper;
    @Autowired
    private ContractMapper contractMapper;

    /**
     * 查询发票详细信息
     * 
     * @param invoiceId 发票主键
     * @return 发票
     */
    @Override
    public SelectInvoiceVo selectInvoiceByInvoiceId(Long invoiceId)
    {
        //初始化返回对象
        SelectInvoiceVo selectInvoiceVo = new SelectInvoiceVo();
        //获取发票信息
        SelectInvoiceVo invoice = invoiceMapper.selectInvoiceByInvoiceId(invoiceId);
        BeanUtils.copyProperties(invoice, selectInvoiceVo);
        //查询合同信息是否存在
        Contract contract = contractMapper.selectContractIsExistByCode(invoice.getContractCode());
        if(contract != null){
            //若存在，状态设为0
            selectInvoiceVo.setContractStatus("0");
            //设置合同文件地址
            selectInvoiceVo.setContractPdfAddress(contract.getPdfAddress());
        }else {
            //若不存在，状态设为1
            selectInvoiceVo.setContractStatus("1");
            //设置合同文件地址
            selectInvoiceVo.setContractPdfAddress(null);
        }
            // 获取发票附件信息并设置文件名
        List<InvoiceAttachment> invoiceAttachments = invoiceAttachmentMapper.selectInvoiceAttachmentByInvoiceId(invoiceId);
        for (InvoiceAttachment invoiceAttachment : invoiceAttachments) {
            String pdfAddress = invoiceAttachment.getPdfAddress();
            String fileName = extractFileName(pdfAddress);
            invoiceAttachment.setName(fileName);
        }
        selectInvoiceVo.setInvoiceAttachmentInfo(invoiceAttachments);
        return selectInvoiceVo;
    }

    // 从路径中提取文件名
    private String extractFileName(String pdfAddress) {
        if (pdfAddress == null) {
            return null;
        }
        // 使用简单的字符串方法提取文件名
        int lastSlashIndex = pdfAddress.lastIndexOf('/');
        return (lastSlashIndex != -1) ? pdfAddress.substring(lastSlashIndex + 1) : pdfAddress;
    }

    /**
     * 查询发票信息-导出发票信息用
     *
     * @param invoiceIds 发票主键
     * @return 发票
     */
    public List<InvoiceExport> selectInvoiceByInvoiceIds(Long[] invoiceIds) {
        List<InvoiceExport> invoiceExports = new ArrayList<>();
        // 全局计数器
        AtomicInteger index = new AtomicInteger(1);
        for (Long invoiceId : invoiceIds) {
            // 获取发票信息
            List<SelectInvoiceVo> invoice = invoiceMapper.selectInvoiceByInvoiceIds(invoiceId);
            if (invoice != null) {
                InvoiceExport invoiceExport = null;
                for (SelectInvoiceVo selectInvoiceVo : invoice) {
                    invoiceExport = new InvoiceExport();
                    // 序号自增
                    invoiceExport.setIndex(index.getAndIncrement());
                    // 设置发票基础信息
                    BeanUtils.copyProperties(selectInvoiceVo, invoiceExport);
                    if (selectInvoiceVo.getSaleCompanyInfoList() != null && !selectInvoiceVo.getSaleCompanyInfoList().isEmpty()) {
                        for (InvoiceInfoVo invoiceInfoVo : selectInvoiceVo.getSaleCompanyInfoList()) {
                            invoiceExport.setSalName(invoiceInfoVo.getName());
                            invoiceExport.setSalTaxNumber(invoiceInfoVo.getTaxNumber());
                            invoiceExport.setSalBank(invoiceInfoVo.getBank());
                            invoiceExport.setSalBankAccount(invoiceInfoVo.getBankAccount());
                        }
                    }
                    if (selectInvoiceVo.getPurchaseCompanyInfoList() != null && !selectInvoiceVo.getPurchaseCompanyInfoList().isEmpty()) {
                        for (InvoiceInfoVo invoiceInfoVo1 : selectInvoiceVo.getPurchaseCompanyInfoList()) {
                            invoiceExport.setName(invoiceInfoVo1.getName());
                            invoiceExport.setTaxNumber(invoiceInfoVo1.getTaxNumber());
                        }
                    }
                }
                invoiceExports.add(invoiceExport);
            }
        }

        return invoiceExports;
    }




    /**
     * 查询发票列表
     * 
     * @param invoice 发票
     * @return 发票
     */
    @Override
    public List<SelectInvoiceVo> selectInvoiceList(Invoice invoice)
    {
        return invoiceMapper.selectInvoiceList(invoice);
    }

    /**
     * 新增发票
     * 
     * @param invoice 发票
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult insertInvoice(Invoice invoice) {
        // 设置添加人id
        invoice.setAddUserId(SecurityUtils.getUserId());
        // 设置添加时间
        invoice.setAddTime(DateUtils.getNowDate());
        // 根据所属公司id获取公司名称
        BelongingCompany belongingCompany = belongingCompanyMinvoiceInformationMapper.selectBelongingCompanyByBelongingCompanyId(invoice.getBelongingCompanyId());
        String companyName = belongingCompany.getName();
        String type = invoice.getType();
        // 根据公司名称、发票类型、当前时间戳生成发票编号
        String code = InvoiceCode.getInvoiceCode(companyName, type);
        // 设置发票编号
        invoice.setCode(code);
        // 处理销方和购方信息
        Long salesInvoiceId = processInvoiceInfo(invoice.getSaleCompanyInfoList());
        Long buyInvoiceId = processInvoiceInfo(invoice.getPurchaseCompanyInfoList());
        if(Objects.equals(salesInvoiceId, buyInvoiceId)){
            return AjaxResult.error("销方和购方信息不能相同");
        }
        // 设置销方和购方信息id
        invoice.setSalesInvoiceId(salesInvoiceId);
        invoice.setBuyInvoiceId(buyInvoiceId);
        // 插入发票信息
        invoiceMapper.insertInvoice(invoice);
        // 处理发票附件信息
        if (invoice.getInvoiceAttachmentInfo() != null) {
            for (InvoiceAttachment invoiceAttachment : invoice.getInvoiceAttachmentInfo()) {
                //通过主键回显获得发票id并设置
                invoiceAttachment.setInvoiceId(invoice.getInvoiceId());
                // 处理销方和购方信息
                Long sellingInvoiceInformationId = processInvoiceInfo(invoiceAttachment.getSaleCompanyInfoList());
                Long buyInvoiceInformationId = processInvoiceInfo(invoiceAttachment.getPurchaseCompanyInfoList());
                if(Objects.equals(sellingInvoiceInformationId, buyInvoiceInformationId)){
                    return AjaxResult.error("发票附件的销方和购方信息不能相同");
                }
                // 设置销方和购方信息id
                invoiceAttachment.setSellingInvoiceInformationId(sellingInvoiceInformationId);
                invoiceAttachment.setBuyInvoiceInformationId(buyInvoiceInformationId);
                // 插入发票附件信息
                invoiceAttachmentMapper.insertInvoiceAttachment(invoiceAttachment);
            }
        }

        return AjaxResult.success("新增成功");
    }

    private Long processInvoiceInfo(List<InvoiceInfoVo> companyInfoList) {
        for (InvoiceInfoVo companyInfo : companyInfoList) {
            InvoiceInformation invoiceInfo = new InvoiceInformation();
            BeanUtils.copyProperties(companyInfo, invoiceInfo);
            InvoiceInformation existingInfo = invoiceInformationMapper.isInvoiceInformation(invoiceInfo);
            if (existingInfo != null) {
                //如果销方、购方信息存在，返回其id
                return existingInfo.getInvoiceInformationId();
            } else {
                //如果销方、购方信息不存在，插入新的信息并返回其id
                invoiceInformationMapper.insertInvoiceInformation(invoiceInfo);
                return invoiceInfo.getInvoiceInformationId();
            }
        }
        return 0L; // 默认值或抛出异常
    }


    /**
     * 修改发票
     * 
     * @param invoice 发票
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult updateInvoice(Invoice invoice)
    {
        // 设置修改人id
        invoice.setUpdateUserId(SecurityUtils.getUserId());
        // 设置修改时间
        invoice.setUpdateTime(DateUtils.getNowDate());
        // 处理销方和购方信息
        Long salesInvoiceId = processInvoiceInfo(invoice.getSaleCompanyInfoList());
        Long buyInvoiceId = processInvoiceInfo(invoice.getPurchaseCompanyInfoList());
        if(Objects.equals(salesInvoiceId, buyInvoiceId)){
            return AjaxResult.error("销方和购方信息不能相同");
        }
        // 设置销方和购方信息id
        invoice.setSalesInvoiceId(salesInvoiceId);
        invoice.setBuyInvoiceId(buyInvoiceId);
        // 修改发票信息
        invoiceMapper.updateInvoice(invoice);
        // 处理发票附件信息
        if (invoice.getInvoiceAttachmentInfo() != null) {
            //先删除发票对应的所有发票附件
            invoiceAttachmentMapper.deleteInvoiceAttachmentByInvoiceId(invoice.getInvoiceId());
            for (InvoiceAttachment invoiceAttachment : invoice.getInvoiceAttachmentInfo()) {
                //设置发票id
                invoiceAttachment.setInvoiceId(invoice.getInvoiceId());
                // 处理销方和购方信息
                Long sellingInvoiceInformationId = processInvoiceInfo(invoiceAttachment.getSaleCompanyInfoList());
                Long buyInvoiceInformationId = processInvoiceInfo(invoiceAttachment.getPurchaseCompanyInfoList());
                if(Objects.equals(sellingInvoiceInformationId, buyInvoiceInformationId)){
                    return AjaxResult.error("发票附件的销方和购方信息不能相同");
                }
                // 设置销方和购方信息id
                invoiceAttachment.setSellingInvoiceInformationId(sellingInvoiceInformationId);
                invoiceAttachment.setBuyInvoiceInformationId(buyInvoiceInformationId);
                invoiceAttachmentMapper.insertInvoiceAttachment(invoiceAttachment);
            }
        }

        return AjaxResult.success("修改成功");
    }

    /**
     * 批量删除发票
     * 
     * @param invoiceIds 需要删除的发票主键
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult deleteInvoiceByInvoiceIds(Long[] invoiceIds) {
        if (invoiceIds == null || invoiceIds.length == 0) {
            return AjaxResult.error("没有提供发票ID");
        }
        // 删除发票信息
        int invoiceDeletedCount = invoiceMapper.deleteInvoiceByInvoiceIds(invoiceIds);
        // 删除发票附件信息
        int attachmentDeletedCount = invoiceAttachmentMapper.deleteInvoiceAttachmentByInvoiceIds(invoiceIds);

        // 检查删除操作是否成功
        if (invoiceDeletedCount > 0 && attachmentDeletedCount >= 0) {
            return AjaxResult.success("删除成功");
        } else {
            return AjaxResult.error("删除失败");
        }
    }

    /**
     * 删除发票信息
     * 
     * @param invoiceId 发票主键
     * @return 结果
     */
    @Override
    public int deleteInvoiceByInvoiceId(Long invoiceId)
    {
        return invoiceMapper.deleteInvoiceByInvoiceId(invoiceId);
    }
}
